#include <stdio.h>
#include <stdlib.h>
#include <gmssl/sm2.h>
#include <gmssl/error.h>
#include <gmssl/pem.h>

int main(int argc, char **argv) {
    if (argc != 3) {
        fprintf(stderr, "Usage: %s <private_key_file> <public_key_file>\n", argv[0]);
        return 1;
    }

    const char *private_key_file = argv[1];
    const char *public_key_file = argv[2];

    SM2_KEY sm2_key;
    FILE *fp;

    // 生成SM2密钥对
    if (sm2_key_generate(&sm2_key) != 1) {
        fprintf(stderr, "Failed to generate SM2 key pair.\n");
        return 1;
    }

    // 保存私钥
    if (!(fp = fopen(private_key_file, "wb"))) {
        perror("Failed to open private key file");
        return 1;
    }
    if (sm2_private_key_info_to_pem(&sm2_key, fp) != 1) {
        fprintf(stderr, "Failed to write private key to file.\n");
        fclose(fp);
        return 1;
    }
    fclose(fp);

    // 保存公钥
    if (!(fp = fopen(public_key_file, "wb"))) {
        perror("Failed to open public key file");
        return 1;
    }
    if (sm2_public_key_info_to_pem(&sm2_key, fp) != 1) {
        fprintf(stderr, "Failed to write public key to file.\n");
        fclose(fp);
        return 1;
    }
    fclose(fp);

    printf("SM2 key pair generated successfully.\n");
    return 0;
}
